package cn.gbase.jiangsu.data.transfer.action;

import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.json.simple.JSONObject;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.QueryResult;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.View;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.filter.CheckSession;
import org.nutz.mvc.view.ServerRedirectView;
import org.nutz.service.IdEntityService;
import org.nutz.trans.Atom;
import org.nutz.trans.Trans;

import cn.gbase.jiangsu.data.transfer.bean.BuildingUnit;
import cn.gbase.jiangsu.data.transfer.bean.Community;
import cn.gbase.jiangsu.data.transfer.bean.CommunityBuilding;
import cn.gbase.jiangsu.data.transfer.bean.Company;
import cn.gbase.jiangsu.data.transfer.bean.CompanyToBuilding;
import cn.gbase.jiangsu.data.transfer.bean.CompanyToSchoolUser;
import cn.gbase.jiangsu.data.transfer.bean.CompanyUser;
import cn.gbase.jiangsu.data.transfer.bean.ForumTopic;
import cn.gbase.jiangsu.data.transfer.bean.Product;
import cn.gbase.jiangsu.data.transfer.bean.ProductComment;
import cn.gbase.jiangsu.data.transfer.bean.ProductOrder;
import cn.gbase.jiangsu.data.transfer.bean.ProductSortTreeNode;
import cn.gbase.jiangsu.data.transfer.bean.ShopUser;
import cn.gbase.jiangsu.data.transfer.bean.ShopUserView;
import cn.gbase.jiangsu.data.transfer.bean.ShopUsersSyncLogin;
import cn.gbase.jiangsu.data.transfer.bean.ShopUsersTrade;
import cn.gbase.jiangsu.data.transfer.bean.Supplier;
import cn.gbase.jiangsu.data.transfer.bean.SupplierToCommunity;
import cn.gbase.jiangsu.data.transfer.bean.SystemLog;
import cn.gbase.jiangsu.data.transfer.bean.UnitRoom;
import cn.gbase.jiangsu.data.transfer.common.Constants;
import cn.gbase.jiangsu.data.transfer.service.BuildingService;
import cn.gbase.jiangsu.data.transfer.service.CompanyService;
import cn.gbase.jiangsu.data.transfer.service.CompanyUserService;
import cn.gbase.jiangsu.data.transfer.service.ForumC2UService;
import cn.gbase.jiangsu.data.transfer.service.ProductService;
import cn.gbase.jiangsu.data.transfer.service.ProductSortTreeNodeService;
import cn.gbase.jiangsu.data.transfer.service.SupplierService;
import cn.gbase.jiangsu.data.transfer.service.SupplierUserService;
import cn.gbase.jiangsu.data.transfer.service.SystemLogService;
import cn.gbase.jiangsu.data.transfer.util.CommonUtil;
import cn.gbase.jiangsu.data.transfer.util.DefaultPasswordEncoder;
import cn.gbase.jiangsu.data.transfer.vo.ReadyProductVO;

import com.google.common.collect.Lists;
import com.google.common.net.HttpHeaders;

@IocBean(args = { "refer:dao" })
@At("/companyAdmin")
@Filters(@By(type = CheckSession.class, args = { "companyUser", "jsp:/companyIndex" }))
public class CompanyAdminAction extends IdEntityService<CompanyUser> {
	@Inject
	private ProductSortTreeNodeService productSortTreeNodeService;
	@Inject("java:$config.get('excelDownPath')")
	private String excelDownPath;
	@Inject
	private SupplierUserService supplierUserService;
	@Inject
	private BuildingService buildingService;
	@Inject
	private ForumC2UService forumC2UService;
	@Inject
	private ProductService productService;
	@Inject
	private CompanyUserService companyUserService;
	@Inject
	private CompanyService companyService;
	@Inject
	private SupplierService supplierService;
	@Inject("java:$config.get('companyUserAclStr')")
	private String companyUserAclStr;
	@Inject("java:$config.get('picUpload')")
	private String path;
	@Inject("java:$config.get('syncPath')")
	private String syncPath;
	private final SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd");
	@Inject
	private SystemLogService systemLogService;

	public CompanyAdminAction() {
		super();
	}

	public CompanyAdminAction(Dao dao) {
		super(dao);
	}

	/**
	 * 用户登录.
	 * 
	 * @param user
	 *            用户数据
	 * @param request
	 * @param session
	 */
	@At("/login")
	@POST
	@Ok(">>:/companyMain")
	@Fail("jsp:/companyIndex")
	@Filters
	public void login(@Param("..") CompanyUser user, HttpServletRequest request, HttpSession session) {

		//回传数据
		request.setAttribute("formdata", user);

		// 取得用户
		CompanyUser u = this.dao().fetch(CompanyUser.class,
				Cnd.where("username", "=", user.getUsername()).and("status", "=", 1));
		// 用户不存在
		if (u == null) {
			request.setAttribute("msg", "用户名不存在");
			throw new RuntimeException();
		}
		Company company = this.dao().fetch(Company.class, u.getCompanyId());
		Community community = this.dao().fetch(Community.class, company.getCommunityId());
		// 密码错误
		String encodePass = new DefaultPasswordEncoder("MD5").encode(user.getPassword());
		if (!u.getPassword().equals(encodePass)) {
			request.setAttribute("msg", "密码错误！");
			throw new RuntimeException();
		}
		session.setAttribute("company", company);
		session.setAttribute("community", community);

		// 保存到session
		session.setAttribute("companyUser", u);

		// 权限名称，初始权限

		String[] aclNameArray = companyUserAclStr.split(",");
		char[] aclArray = u.getAclStr().toCharArray();
		String[] aclList = new String[aclArray.length];
		for (int i = 0; i < aclArray.length; i++) {
			aclList[i] = String.valueOf(aclArray[i]);
		}
		// 权限
		session.setAttribute("companyAclNameArray", aclNameArray);
		session.setAttribute("companyAclArray", aclList);

		SystemLog logger = new SystemLog();
		logger.setOperatorId(u.getId());
		logger.setOperType(1);
		//3是物业平台
		logger.setOperModular(3);
		logger.setOperContent("物业用户" + u.getUsername() + "登录物业平台");
		systemLogService.addSystemLog(logger);
	}

	/**
	 * 到注册页面.
	 * 
	 * @param back
	 * @param request
	 */
	@At("/toReg")
	@Ok("jsp:/company/reg")
	@Filters
	public void toReg(@Param("back") String back, HttpServletRequest request, HttpSession session) {
		CompanyUser loginUser = (CompanyUser) session.getAttribute("companyUser");
		Company company = companyService.getCompany(loginUser.getCompanyId());

		List<Community> communityList = companyService.getCommunity(company.getId());
		List<CommunityBuilding> building = companyService.getBuilding(loginUser.getCompanyId());
		request.setAttribute("communityList", communityList);
		request.setAttribute("buildingList", building);
		// 回传数据
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("sex", "0");
		request.setAttribute("formdata", itemMap);

	}

	/**
	 * 用户注册.
	 * 
	 * @param user
	 *            用户数据
	 * @param request
	 * @param session
	 */
	@At("/reg")
	@POST
	@Fail("jsp:/company/reg")
	@Ok("jsp:/company/regOK")
	public void doReg(@Param("..") ShopUser user, HttpServletRequest request, HttpSession session) {
		CompanyUser loginUser = (CompanyUser) session.getAttribute("companyUser");
		Company company = companyService.getCompany(loginUser.getCompanyId());
		Community communityReal = this.dao().fetch(Community.class, company.getCommunityId());

		user.setUsername(user.getMobile());
		// 回传数据
		request.setAttribute("formdata", user);
		// 校区的话，要根据一卡通号码，自动创建楼、单元、房间
		if (user.getUserType() == 2) {
			// 等到保存用户后，再创建
			user.setCompanyId(loginUser.getCompanyId());
		} else {
			// 检查房间是否存在
			int roomId = user.getRoomId();
			UnitRoom room = this.dao().fetch(UnitRoom.class, roomId);
			if (room == null || room.getDeleteFlag() == 1) {
				throw new RuntimeException("无此房间。");
			}

			// 检查房间是否被占用
			int count = this.dao().count(ShopUser.class, Cnd.where("roomId", "=", roomId).and("deleteFlag", "=", 0));
			if (count > 0) {
				// 看小区是否允许一个房间多个用户
				Community communityByRoom = buildingService.getCommunityByRoom(Integer.valueOf(user.getBindCode()));
				if (0 == communityByRoom.getAllowOneRoomMultiUser()) {
					throw new RuntimeException("该房间已经绑定用户。");
				}
			}
		}
		// 取得用户
		ShopUser u = this.dao().fetch(ShopUser.class,
				Cnd.where("username", "=", user.getUsername()).and("deleteFlag", "=", 0));

		// 用户名存在
		if (u != null) {
			request.setAttribute("errmsg", "用户名已存在，请更换。");
			throw new RuntimeException();
		}
		if (user.getUserType() == 2) {
			// 比如天津第一轻工业学校，前4位是：06（学校）01（天津第一轻工业学校红桥校区），
			// 如果一个学生的一卡通号码是：3456765，补充为9位：003456765
			// 按照原先的3+2+4的方式写到数据库里（楼的代码3位，单元代码2位，房间号代码4位）
			String cardNo = user.getOneCardNo();
			if ((cardNo == null) || (cardNo.length() == 0)) {
				cardNo = "001234567";
				user.setOneCardNo(cardNo);
			}
			cardNo = ("000000000" + cardNo).substring(cardNo.length());

			// 拆分
			String buildingNo = cardNo.substring(0, 3);
			String unitNo = cardNo.substring(3, 5);
			String roomNo = cardNo.substring(5);

			// 创建
			if (!companyUserService.isRoomExist(communityReal.getId(), buildingNo, unitNo, roomNo)) {
				UnitRoom room = new UnitRoom();
				room.setCommunityId(communityReal.getId()); // 社区ID
				room.setBuildingNo(buildingNo);
				room.setUnitNo(unitNo);
				room.setRoomNo(roomNo);
				room = companyUserService.addRoom(room);

				// 房间ID设置到用户属性中
				user.setRoomId(room.getId());
			} else {

				// 房间ID设置到用户属性中
				List<UnitRoom> roomList = companyUserService.getRoomList(1, "" + communityReal.getId(), buildingNo,
						unitNo, roomNo).getList(UnitRoom.class);
				user.setRoomId(roomList.get(0).getId());
			}
		}
		// 注册用户
		try {
			companyUserService.regUser(user);
		} catch (RuntimeException e) {
			request.setAttribute("errmsg", e.getMessage());
			throw new RuntimeException();
		}

		// 保存到session
		// session.setAttribute("shopUser", u);
	}

	/**
	 * 验证注册码是否有效.
	 */
	@At("/validateCode")
	@Ok("json")
	@Filters
	public Map<String, String> validateCode(@Param("code") String code) {
		return companyUserService.validateCode(code);
	}

	@At("/logout")
	@Ok("jsp:/companyIndex")
	@Filters
	public void logout(HttpServletRequest request, HttpSession session) {
		CompanyUser u = (CompanyUser) session.getAttribute("companyUser");
		if (u != null) {
			SystemLog logger = new SystemLog();
			logger.setOperatorId(u.getId());
			logger.setOperType(1);
			//4是供货商平台
			logger.setOperModular(3);
			logger.setOperContent("物业用户" + u.getUsername() + "退出物业平台");
			systemLogService.addSystemLog(logger);
			session.removeAttribute("companyUser");
		}
	}

	/**
	 * 跳转到修改密码页面.
	 */
	@At("/toUpdatePW")
	@Ok("jsp:/company/updatePW")
	public void toUpdatePage() {
	}

	/**
	 * 要代购
	 */
	@At("/toShopCard")
	@Ok("jsp:/product/buyListProduct")
	public void toShopCard(HttpServletRequest request, HttpSession session) {
		CompanyUser loginUser = (CompanyUser) session.getAttribute("companyUser");
		Company company = companyService.getCompany(loginUser.getCompanyId());
		List<Community> communityList = companyService.getCommunity(company.getId());
		List<CommunityBuilding> building = companyService.getBuilding(loginUser.getCompanyId());
		request.setAttribute("communityList", communityList);
		request.setAttribute("buildingList", building);
	}

	@At("/exportSchoolUser")
	@Ok("void")
	public void exportSchoolUser(HttpServletRequest request, HttpServletResponse response, HttpSession session)
			throws Exception {
		// 取得物业用户
		CompanyUser loginUser = (CompanyUser) session.getAttribute("companyUser");
		String html = companyUserService.exportSchoolUser(loginUser.getCompanyId(), null, null, null, null);
		if (StringUtils.isNotBlank(html)) {
			// 生成表格
			response.setContentType("applicationnd.ms-excel");
			response.addHeader("Content-Disposition", "attachment; filename=\"" + "cardNo.xls" + "\"");

			try {
				response.getWriter().print(html);
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	@At("/exportUser")
	@Ok("void")
	public void exportUser(HttpServletRequest request, HttpServletResponse response, HttpSession session)
			throws Exception {
		// 取得物业用户
		CompanyUser loginUser = (CompanyUser) session.getAttribute("companyUser");
		Company company = companyService.getCompany(loginUser.getCompanyId());
		String html = companyUserService.exportUser(loginUser.getCompanyId(), null, null, null, null);
		if (StringUtils.isNotBlank(html)) {
			// 生成表格
			response.setContentType("applicationnd.ms-excel");
			response.addHeader("Content-Disposition", "attachment; filename=\"" + "cardNo.xls" + "\"");

			try {
				response.getWriter().print(html);
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	/**
	 * 校区会员信息
	 */
	@At("/listSchoolUser")
	@Ok("jsp:/company/userSchoolList")
	public QueryResult listSchoolUser(@Param("p") int pageNumber, @Param("status") String status,
			HttpServletRequest request, HttpSession session) {
		// 取得物业用户
		CompanyUser loginUser = (CompanyUser) session.getAttribute("companyUser");
		Company company = companyService.getCompany(loginUser.getCompanyId());
		Community communityReal = this.dao().fetch(Community.class, company.getCommunityId());

		List<Community> communityList = new ArrayList<Community>();
		communityList.add(communityReal);
		//		companyService.getCommunity(company.getId());
		//		List<CommunityBuilding> building = companyService.getBuilding(loginUser.getCompanyId());
		request.setAttribute("communityList", communityList);
		//		request.setAttribute("buildingList", building);
		// 回传数据
		Map<String, String> itemMap = new HashMap<String, String>();
		//小区
		String community = request.getParameter("community");
		//一卡通
		String oneCardNo = request.getParameter("oneCardNo");
		//用户名
		String username = request.getParameter("username");
		//手机号
		String mobile = request.getParameter("mobile");
		// 回传表单输入
		itemMap.put("community", community);
		itemMap.put("oneCardNo", oneCardNo);
		itemMap.put("username", username);
		itemMap.put("mobile", mobile);
		itemMap.put("status", status);
		request.setAttribute("formdata", itemMap);
		pageNumber = pageNumber == 0 ? 1 : pageNumber;
		return companyUserService.listSchoolUser(loginUser.getCompanyId(), community, oneCardNo, username, mobile,
				status, pageNumber);

	}

	/**
	 * 审核会员
	 */
	@At("/editUser")
	@Ok("json")
	public String editUser(@Param("id") int id) {
		// 取得会员信息
		this.dao().update(ShopUser.class, Chain.make("status", 1), Cnd.where("id", "=", id));
		return "{id:0}";
	}

	/**
	 * 审核用户.
	 */
	@At("/editUserByIds")
	@Ok("json")
	public String editUserByIds(@Param("idStr") String idStr, HttpSession session) {
		String[] idArray = idStr.split(",");
		for (String id : idArray) {
			this.dao().update(ShopUser.class, Chain.make("status", 1), Cnd.where("id", "=", id));
		}
		return "{id:0}";
	}

	/**
	 * 会员卡储值
	 */
	@At("/toAddTrade")
	@Ok("jsp:/company/addUserTrade")
	public void toAddTrade(HttpServletRequest request, HttpSession session) {
		CompanyUser loginUser = (CompanyUser) session.getAttribute("companyUser");
		Company company = companyService.getCompany(loginUser.getCompanyId());
		List<Community> communityList = companyService.getCommunity(company.getId());
		List<CommunityBuilding> building = companyService.getBuilding(loginUser.getCompanyId());
		request.setAttribute("communityList", communityList);
		request.setAttribute("buildingList", building);
	}

	/**
	 * 修改密码.
	 * @param user 用户信息
	 * @param request
	 * @param session
	 */
	@At("/updatePW")
	@POST
	@Ok(">>:/companyAdmin/ok")
	@Fail("jsp:/company/updatePW")
	public void add(@Param("..") CompanyUser user, HttpServletRequest request, HttpSession session) {

		// 取得用户
		CompanyUser loginUser = (CompanyUser) session.getAttribute("companyUser");

		//输入密码加密
		String encodePass = new DefaultPasswordEncoder("MD5").encode(user.getPassword());

		//比较
		if (!encodePass.equals(loginUser.getPassword())) {
			request.setAttribute("msg", "密码输入错误");
			throw new RuntimeException();
		}
		user.setId(loginUser.getId());
		companyUserService.updatePWS(user);
		SystemLog logger = new SystemLog();
		logger.setOperatorId(loginUser.getId());
		logger.setOperType(1);
		//3是物业平台
		logger.setOperModular(3);
		logger.setOperContent("物业用户" + loginUser.getUsername() + "修改密码");
		systemLogService.addSystemLog(logger);
	}

	@At("/ok")
	@Ok("jsp:/company/ok")
	public void toOkPage(HttpServletRequest request) {
	}

	@At("/companyListUser")
	@Ok("jsp:/company/listCompanyUser")
	public QueryResult companyListUser(@Param("sid") int sid, @Param("p") int pageNumber,
			@Param("username") String username, @Param("realname") String realname, HttpServletRequest request,
			HttpSession session) {
		// 取得用户
		CompanyUser loginUser = (CompanyUser) session.getAttribute("companyUser");

		// 回传表单输入
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("username", username);
		itemMap.put("realname", realname);
		itemMap.put("sid", "" + loginUser.getCompanyId());
		request.setAttribute("formdata", itemMap);

		// 查询数据
		QueryResult list = companyUserService.getUserList(pageNumber, username, realname, sid, loginUser.getId());

		return list;
	}

	@At("/toAddUser")
	@Ok("jsp:/company/editCompanyUser")
	public void toAddPage(@Param("sid") int sid, HttpServletRequest request, HttpSession session) {

		// 回传表单输入
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("companyId", "" + sid); // 物业ID
		request.setAttribute("formdata", itemMap);

		//所有权限
		String[] aclNameArray = companyUserAclStr.split(",");
		List<String> aclNameArrayUser = Lists.newArrayList();
		//登录人的所有权限
		String[] aclList = (String[]) session.getAttribute("companyAclArray");
		for (int i = 0; i < aclList.length; i++) {
			if ("1".equals(aclList[i]))
				aclNameArrayUser.add(aclNameArray[i]);
		}
		// 维护用户的所有权限
		String[] aclListUser = new String[aclList.length];
		// 权限
		request.setAttribute("companyAclNameArrayUser", aclNameArrayUser);
		request.setAttribute("companyAclArrayUser", aclListUser);

	}

	@At("/addUser")
	@POST
	@Ok(">>:/companyAdmin/companyListUser?p=1")
	@Fail("jsp:/company/editCompanyUser")
	public CompanyUser addUser(@Param("..") CompanyUser user, HttpServletRequest request, HttpSession session) {
		// 取得用户
		CompanyUser loginUser = (CompanyUser) session.getAttribute("companyUser");
		user.setCompanyId(loginUser.getCompanyId());
		// 回传表单输入
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("companyId", "" + loginUser.getCompanyId()); // 物业ID
		request.setAttribute("formdata", itemMap);

		//所有权限
		String[] aclNameArray = companyUserAclStr.split(",");
		List<String> aclNameArrayUser = Lists.newArrayList();
		//登录人的所有权限
		String[] aclList = (String[]) session.getAttribute("companyAclArray");
		for (int i = 0; i < aclList.length; i++) {
			if ("1".equals(aclList[i]))
				aclNameArrayUser.add(aclNameArray[i]);
		}
		// 维护用户的所有权限
		String[] aclListUser = new String[aclList.length];
		// 权限
		request.setAttribute("companyAclNameArrayUser", aclNameArrayUser);
		request.setAttribute("companyAclArrayUser", aclListUser);
		if (!companyUserService.addOrUpdUser(user)) {
			request.setAttribute("errmsg", "该用户名的用户已经存在。"); // 错误信息
			request.setAttribute("formdata", user); // 表单数据
			throw new RuntimeException();
		}
		SystemLog logger = new SystemLog();
		logger.setOperatorId(loginUser.getId());
		logger.setOperType(1);
		//3是物业平台
		logger.setOperModular(3);
		logger.setOperContent("物业用户" + loginUser.getUsername() + "维护用户信息：" + user.getUsername());
		systemLogService.addSystemLog(logger);
		return user;
	}

	@At("/toEditUser")
	@Ok("jsp:/company/editCompanyUser")
	public void toEditPage(@Param("id") int userId, HttpServletRequest request, HttpSession session) {

		// 取得用户数据，放入表单中
		CompanyUser user = companyUserService.getUser(userId);
		request.setAttribute("formdata", user);
		//所有权限
		String[] aclNameArray = companyUserAclStr.split(",");
		List<String> aclNameArrayUser = Lists.newArrayList();
		//登录人的所有权限
		String[] aclList = (String[]) session.getAttribute("companyAclArray");
		for (int i = 0; i < aclList.length; i++) {
			if ("1".equals(aclList[i]))
				aclNameArrayUser.add(aclNameArray[i]);
		}
		// 维护用户的所有权限
		char[] aclArray = user.getAclStr().toCharArray();
		String[] aclListUser = new String[aclArray.length];
		for (int i = 0; i < aclArray.length; i++) {
			aclListUser[i] = String.valueOf(aclArray[i]);
		}
		// 权限
		request.setAttribute("companyAclNameArrayUser", aclNameArrayUser);
		request.setAttribute("companyAclArrayUser", aclListUser);
	}

	/**
	 * 删除用户.
	 */
	@At("/deleteUser")
	@Ok("json")
	public String deleteUser(@Param("id") int id, HttpSession session) {
		// 取得用户
		CompanyUser loginUser = (CompanyUser) session.getAttribute("companyUser");
		companyUserService.deleteUser(id);
		SystemLog logger = new SystemLog();
		logger.setOperatorId(loginUser.getId());
		logger.setOperType(1);
		//3是物业平台
		logger.setOperModular(3);
		logger.setOperContent("物业用户" + loginUser.getUsername() + "删除id为" + id + "的用户");
		systemLogService.addSystemLog(logger);
		return "{id:0}";
	}

	/**
	 * 确认用户.
	 */
	@At("/showUser")
	@Ok("jsp:/company/userDetail")
	public ShopUserView showUser(@Param("uid") String uid, HttpSession session) {
		// 取得会员信息
		ShopUserView u = this.dao().fetch(ShopUserView.class, Cnd.where("id", "=", uid));
		return u;
	}

	/**
	 * 确认用户.
	 */
	@At("/checkUser")
	@Ok("json")
	public String checkUser(@Param("community") String community, @Param("buildNo") String buildNo,
			@Param("unitNo") String unitNo, @Param("roomNo") String roomNo, @Param("mobile") String mobile,
			HttpSession session) {
		// 取得物业用户

		ShopUserView view = companyUserService.checkUser(community, buildNo, unitNo, roomNo, mobile);
		JSONObject obj = new JSONObject();
		if (view == null)
			obj.put("error", "无此会员用户");
		else {
			obj.put("id", view.getId());
			obj.put("realName", view.getRealName());
			obj.put("rid", view.getRoomId());
			obj.put("accountBalance", view.getAccountBalance());
		}
		return obj.toJSONString();
	}

	/**
	 * 确认楼层.
	 */
	@At("/checkBuilding")
	public Object checkBuilding(@Param("community") String community, HttpSession session) {
		// 取得物业用户
		CompanyUser loginUser = (CompanyUser) session.getAttribute("companyUser");
		List<CommunityBuilding> building = companyService.getBuilding(loginUser.getCompanyId());
		JSONObject obj = new JSONObject();
		if (building == null)
			obj.put("error", "无楼层");
		else {
			return building;
		}
		return obj.toJSONString();
	}

	/**
	 * 确认单元.
	 */
	@At("/checkUnit")
	public Object checkUnit(@Param("build") String build, HttpSession session) {
		// 取得物业用户
		CompanyUser loginUser = (CompanyUser) session.getAttribute("companyUser");
		List<BuildingUnit> unitList = companyService.getUnit(Integer.valueOf(build));
		JSONObject obj = new JSONObject();
		if (unitList == null)
			obj.put("error", "无楼层");
		else {
			return unitList;
		}
		return obj.toJSONString();
	}

	/**
	 * 确认门牌.
	 */
	@At("/checkRoom")
	public Object checkRoom(@Param("unit") String unit, HttpSession session) {
		// 取得物业用户
		CompanyUser loginUser = (CompanyUser) session.getAttribute("companyUser");
		List<UnitRoom> roomList = companyService.getRoom(Integer.valueOf(unit));
		JSONObject obj = new JSONObject();
		if (roomList == null)
			obj.put("error", "无楼层");
		else {
			return roomList;
		}
		return obj.toJSONString();
	}

	/**
	 * 删除多个用户.
	 */
	@At("/deleteManyUser")
	@Ok("json")
	public String deleteManyUser(@Param("idStr") String idStr, HttpSession session) {
		// 取得用户
		CompanyUser loginUser = (CompanyUser) session.getAttribute("companyUser");
		String[] idArray = idStr.split(",");
		for (String id : idArray) {
			companyUserService.deleteUser(Integer.valueOf(id));
			SystemLog logger = new SystemLog();
			logger.setOperatorId(loginUser.getId());
			logger.setOperType(1);
			//4是物业平台
			logger.setOperModular(3);
			logger.setOperContent("物业用户" + loginUser.getUsername() + "删除id为" + id + "的用户");
			systemLogService.addSystemLog(logger);
		}
		return "{id:0}";
	}

	/**
	 * 跳转到供货商首页.
	 */
	@At("/main")
	@Ok("jsp:/companyMain")
	public void toMainPage() {
	}

	/**
	 * 分页查询属于物业小区的所有供应商商品.
	 * 
	 * @param currentPage
	 * @param groupId
	 * @param addTime
	 * @param keyword
	 * @param req
	 */
	@At("/listProduct")
	@Ok("jsp:/shop/product/listProduct")
	public QueryResult listProduct(@Param("sid") int sid, @Param("p") int pageNumber, @Param("keyword") String keyword,
			@Param("nodeId") String nodeId, @Param("selectedNodeName") String selectedNodeName,
			@Param("passStatus") String passStatus, @Param("supplierId") String supplierId, HttpServletRequest request) {

		// 回传表单输入
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("sid", "" + sid);
		itemMap.put("keyword", keyword);
		itemMap.put("nodeId", nodeId);

		itemMap.put("selectedNodeName", selectedNodeName);
		itemMap.put("passStatus", passStatus);
		itemMap.put("supplierId", supplierId);
		request.setAttribute("formdata", itemMap);

		//		Company company = companyService.getCompany(sid);
		// 商品分类
		String json = productService.getTreeJsonDataForZTree(1);
		request.setAttribute("treedata", json);
		// 供应商列表
		List<Integer> supplierIds = supplierService.getSuppliers(Integer.valueOf(sid));
		//		supplierService
		return productService.getProductList(pageNumber, null, keyword, nodeId, passStatus, supplierIds);

	}

	/**
	 * 跳转到修改商品页面.
	 */
	@At("/toShowProduct")
	@Ok("jsp:/product/showProduct")
	public void toShowProduct(@Param("id") int id, @Param("add") boolean flag, HttpServletRequest req) {
		// 回传表单输入
		//				Map<String, String> itemMap = new HashMap<String, String>();
		//				itemMap.put("cardNo", cardNo);

		// 要展示的商品
		Product p = productService.getProductById(id);
		p.setNodeId(p.getProductSort());
		ProductSortTreeNode node = productSortTreeNodeService.getStandTreeNode(p.getProductSort());
		if (node != null) {
			p.setSelectedNodeName(node.getName());
		}
		req.setAttribute("formdata", p);

		// 商品分类
		String json = productService.getTreeJsonDataForZTree(1);
		req.setAttribute("add", flag);
		req.setAttribute("treedata", json);
	}

	/**
	 * 代购进入商城
	 * @param request
	 * @param session
	 * @return
	 */
	@At("/intoShopBuy")
	public View intoShopBuy(HttpServletRequest request, HttpSession session) {
		CompanyUser loginUser = (CompanyUser) session.getAttribute("companyUser");
		// 回传数据
		Map<String, String> itemMap = new HashMap<String, String>();
		//购买会员号
		String userNo = request.getParameter("userNo");
		path = syncPath;
		// 取得用户
		ShopUser u = this.dao().fetch(ShopUser.class, Cnd.where("id", "=", userNo));
		ShopUsersSyncLogin sus = new ShopUsersSyncLogin();
		sus.setOperatorId(loginUser.getId());
		sus.setUserId(u.getId());
		String code = CommonUtil.getRandomNumString(32);
		sus.setLoginCode(code);
		this.dao().insert(sus);
		request.setAttribute("code", code);
		request.setAttribute("syncPath", path);
		return new ServerRedirectView(syncPath + code);

	}

	/**
	 * 会员储值
	 * @param request
	 * @param session
	 * @return
	 */
	@At("/addAccountBalance")
	@Ok("jsp:/company/addUserTrade")
	public QueryResult addAccountBalance(@Param("p") int currentPage, final HttpServletRequest request,
			final HttpSession session) {
		final Dao dao = this.dao();
		//购买会员号
		final String userNo = request.getParameter("userNo");
		// 取得用户
		final ShopUser u = dao.fetch(ShopUser.class, Cnd.where("id", "=", userNo));
		Trans.exec(new Atom() {
			@Override
			public void run() {
				// 回传数据
				Map<String, String> itemMap = new HashMap<String, String>();
				CompanyUser loginUser = (CompanyUser) session.getAttribute("companyUser");
				//小区
				String community = request.getParameter("community");
				//楼号
				String buildNo = request.getParameter("buildNo");
				//单元号
				String unitNo = request.getParameter("unitNo");
				//门牌号
				String roomNo = request.getParameter("roomNo");
				//单据号
				String postNo = request.getParameter("postNo");
				//pos票号
				String posNum = request.getParameter("posNum");
				//余额
				String accountBalance = request.getParameter("accountBalance");
				//储值金额
				String balanceMoney = request.getParameter("money");
				// 回传表单输入
				itemMap.put("community", community);
				itemMap.put("buildNo", buildNo);
				itemMap.put("unitNo", unitNo);
				itemMap.put("userNo", userNo);
				itemMap.put("roomNo", roomNo);
				Company company = companyService.getCompany(loginUser.getCompanyId());
				List<Community> communityList = companyService.getCommunity(company.getId());
				request.setAttribute("communityList", communityList);

				//会员名
				String realName = u.getRealName();
				itemMap.put("realName", realName);
				if (balanceMoney != null && balanceMoney.length() > 0) {
					//final BigDecimal trade = new BigDecimal(0);

					//要加事务*********************

					int rebate = companyService.getRebate(new BigDecimal(balanceMoney));
					BigDecimal trade = new BigDecimal(balanceMoney).multiply(new BigDecimal(rebate)).divide(
							new BigDecimal(100), 0, BigDecimal.ROUND_HALF_UP);
					ShopUsersTrade sut = new ShopUsersTrade();
					sut.setCreateTime(new Date());
					sut.setOperatorId(loginUser.getId());
					sut.setSeqNumber(postNo);
					sut.setPosNum(posNum);
					sut.setStatus(1);
					sut.setUserId(u.getId());
					sut.setTradeType(Constants.TRADE_TYPE_REBATE_COMANY);
					sut.setTradeMoney(trade);
					BigDecimal balance = u.getAccountBalance() == null ? BigDecimal.ZERO : u.getAccountBalance();
					sut.setBalanceMoney(balance.add(new BigDecimal(balanceMoney)).add(trade));
					if (trade.compareTo(new BigDecimal(0)) == 1) {
						dao.insert(sut);
					}
					ShopUsersTrade sutNew = sut;
					sutNew.setTradeType(Constants.TRADE_TYPE_STATION_RECHARGE);
					sutNew.setTradeMoney(new BigDecimal(balanceMoney));
					dao.insert(sutNew);
					if (balance == null) {
						u.setAccountBalance(BigDecimal.valueOf(0));
					} else {
						u.setAccountBalance(balance.add(new BigDecimal(balanceMoney)).add(trade));
					}
					dao.update(u);
				}

				String tradeSum = companyService.getTradeSum(u.getId(), 1);
				itemMap.put("tradeSum", tradeSum);
				BigDecimal balance = u.getAccountBalance();
				if (balance == null)
					balance = BigDecimal.valueOf(0);
				itemMap.put("accountBalance", balance.toString());
				request.setAttribute("formdata", itemMap);
			}
		});
		return companyService.getTradeList(currentPage, u.getId(), Constants.TRADE_TYPE_STATION_RECHARGE);
	}

	/**
	 * 会员储值
	 * @param request
	 * @param session
	 * @return
	 */
	@At("/showAccountBalance")
	@Ok("jsp:/company/showUserTrade")
	public QueryResult showAccountBalance(@Param("p") int currentPage, HttpServletRequest request, HttpSession session) {
		CompanyUser loginUser = (CompanyUser) session.getAttribute("companyUser");
		// 回传数据
		Map<String, String> itemMap = new HashMap<String, String>();

		//购买会员号
		String userNo = request.getParameter("userNo");

		// 回传表单输入

		itemMap.put("userNo", userNo);

		// 取得用户
		ShopUser u = this.dao().fetch(ShopUser.class, Cnd.where("id", "=", userNo));
		//会员名
		String realName = u.getRealName();
		itemMap.put("realName", realName);

		String tradeSum = companyService.getTradeSum(u.getId(), 3);
		itemMap.put("tradeSum", tradeSum);
		BigDecimal balance = u.getAccountBalance();
		if (balance == null)
			balance = BigDecimal.valueOf(0);
		itemMap.put("accountBalance", balance.toString());
		request.setAttribute("formdata", itemMap);
		return companyService.getTradeList(currentPage, u.getId(), 3);
	}

	/**
	 * 查已发货.
	 * 
	 * 
	 */
	@At("/readylistOrder")
	@Ok("jsp:/product/listCompanySupplier")
	public void readylistOrder(@Param("p") int currentPage, @Param("startTime") String startTime,
			HttpServletRequest request, HttpSession session) {
		CompanyUser u = (CompanyUser) session.getAttribute("companyUser");
		// 回传表单输入
		Map<String, String> itemMap = new HashMap<String, String>();
		if (StringUtils.isBlank(startTime))
			startTime = sfd.format(new Date());
		itemMap.put("startTime", startTime);
		request.setAttribute("formdata", itemMap);
		// 订单列表
		List<Supplier> supplierList = companyService.getOrderSupplier(u.getCompanyId(), startTime + " 00:00:00",
				startTime + " 23:59:59", Constants.ORDER_STATUS_SHIPPED);
		request.setAttribute("supplierList", supplierList);

	}

	/**
	 * 会员信息
	 */
	@At("/listUser")
	@Ok("jsp:/company/userList")
	public QueryResult listUser(@Param("p") int pageNumber, HttpServletRequest request, HttpSession session) {
		// 取得物业用户
		CompanyUser loginUser = (CompanyUser) session.getAttribute("companyUser");
		Company company = companyService.getCompany(loginUser.getCompanyId());
		List<Community> communityList = companyService.getCommunity(company.getId());
		List<CommunityBuilding> building = companyService.getBuilding(loginUser.getCompanyId());
		request.setAttribute("communityList", communityList);
		request.setAttribute("buildingList", building);
		// 回传数据
		Map<String, String> itemMap = new HashMap<String, String>();
		//小区
		String community = request.getParameter("community");
		//楼号
		String buildNo = request.getParameter("buildNo");
		//单元号
		String unitNo = request.getParameter("unitNo");
		//门牌号
		String roomNo = request.getParameter("roomNo");
		//购买会员号
		String userNo = request.getParameter("userNo");
		// 回传表单输入
		itemMap.put("community", community);
		itemMap.put("buildNo", buildNo);
		itemMap.put("unitNo", unitNo);
		itemMap.put("userNo", userNo);
		itemMap.put("roomNo", roomNo);
		request.setAttribute("formdata", itemMap);
		return companyUserService.listUser(loginUser.getCompanyId(), community, buildNo, unitNo, roomNo, pageNumber);

	}

	//导出签收单
	@At("/exportUser")
	@Ok("void")
	public void generalExcelForQuery(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		CompanyUser loginUser = (CompanyUser) session.getAttribute("companyUser");
		Company company = companyService.getCompany(loginUser.getCompanyId());
		Community communityReal = this.dao().fetch(Community.class, company.getCommunityId());
		List<Integer> communityIds = new ArrayList<Integer>();
		List<CompanyToBuilding> building = new ArrayList<CompanyToBuilding>();
		List<CompanyToSchoolUser> ids = new ArrayList<CompanyToSchoolUser>();
		//是校区
		if (2 == communityReal.getCommunityType()) {
			ids = this.dao().query(CompanyToSchoolUser.class, Cnd.where(Cnd.exps("companyId", "=", company.getId())),
					null);
			communityIds.add(communityReal.getId());
		} else {
			building = companyService.getCompanyToCommunity(company.getId());
			for (CompanyToBuilding buildCompany : building) {
				CommunityBuilding build = this.dao().fetch(CommunityBuilding.class, buildCompany.getBuildingId());
				communityIds.add(build.getCommunityId());
			}
		}
		List<SupplierToCommunity> supplierCompanyList = this.dao().query(SupplierToCommunity.class,
				Cnd.where("communityId", "in", communityIds));
		List<Integer> supplierIds = new ArrayList<Integer>();
		for (SupplierToCommunity stc : supplierCompanyList)
			supplierIds.add(stc.getSupplierId());
		List<Supplier> supplierList = this.dao().query(Supplier.class,
				Cnd.where("id", "in", supplierIds).and("offlineFlag", "=", Constants.ON_LINE));

		// 订单列表
		List<ProductOrder> result = companyService.getOrderUser(Constants.ORDER_ARRIVE_STATION, building, ids);
		if (result != null && result.size() > 0) {

			String dateStr = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			String encodedfileName = dateStr + ".xls";
			response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedfileName + "\"");
			try {
				OutputStream out = response.getOutputStream();
				companyService.generalExcel(result, out);
				out.flush();
			} catch (IOException e) {

			}

		}

	}

	/**
	 * 以往订单列表.
	 * 
	 * @param currentPage
	 * @param orderCode
	 * @param startTime
	 * @param endTime
	 * @param status
	 * @param request
	 * @return
	 */
	@At("/listOrderNew")
	@Ok("jsp:/product/newCompanyOrder")
	public QueryResult listOrderNew(@Param("p") int currentPage, @Param("orderCode") String orderCode,
			@Param("startTime") String startTime, @Param("supName") String supName, @Param("status") String status,
			@Param("address") String address, @Param("endTime") String endTime, HttpServletRequest request,
			HttpSession session) {
		CompanyUser loginUser = (CompanyUser) session.getAttribute("companyUser");
		Company company = companyService.getCompany(loginUser.getCompanyId());
		Community communityReal = this.dao().fetch(Community.class, company.getCommunityId());
		List<Integer> communityIds = new ArrayList<Integer>();
		List<CompanyToBuilding> building = new ArrayList<CompanyToBuilding>();
		List<CompanyToSchoolUser> ids = new ArrayList<CompanyToSchoolUser>();
		//是校区
		if (2 == communityReal.getCommunityType()) {
			ids = this.dao().query(CompanyToSchoolUser.class, Cnd.where(Cnd.exps("companyId", "=", company.getId())),
					null);
			communityIds.add(communityReal.getId());
		} else {
			building = companyService.getCompanyToCommunity(company.getId());
			for (CompanyToBuilding buildCompany : building) {
				CommunityBuilding build = this.dao().fetch(CommunityBuilding.class, buildCompany.getBuildingId());
				communityIds.add(build.getCommunityId());
			}
		}
		List<SupplierToCommunity> supplierCompanyList = this.dao().query(SupplierToCommunity.class,
				Cnd.where("communityId", "in", communityIds));
		List<Integer> supplierIds = new ArrayList<Integer>();
		for (SupplierToCommunity stc : supplierCompanyList)
			supplierIds.add(stc.getSupplierId());
		List<Supplier> supplierList = this.dao().query(Supplier.class,
				Cnd.where("id", "in", supplierIds).and("offlineFlag", "=", Constants.ON_LINE));

		request.setAttribute("supplierList", supplierList);
		// 回传表单输入
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("orderCode", orderCode);
		itemMap.put("supName", supName);
		itemMap.put("startTime", startTime);
		itemMap.put("endTime", endTime);
		itemMap.put("status", status);
		itemMap.put("address", address);
		request.setAttribute("formdata", itemMap);

		// 订单列表
		return companyService.getOldOrderList(currentPage, orderCode, status, supName, building, startTime, endTime,
				ids, address);
	}

	/**
	 * 订单列表.
	 * 
	 * @param currentPage
	 * @param orderCode
	 * @param startTime
	 * @param endTime
	 * @param status
	 * @param request
	 * @return
	 */
	@At("/listOrder")
	@Ok("jsp:/product/manageCompanyOrder")
	public QueryResult listOrder(@Param("p") int currentPage, @Param("orderCode") String orderCode,
			@Param("supName") String supName, @Param("status") String status, @Param("startTime") String startTime,
			@Param("address") String address, @Param("endTime") String endTime, HttpServletRequest request,
			HttpSession session) {
		CompanyUser loginUser = (CompanyUser) session.getAttribute("companyUser");
		Company company = companyService.getCompany(loginUser.getCompanyId());
		Community communityReal = this.dao().fetch(Community.class, company.getCommunityId());
		List<Integer> communityIds = new ArrayList<Integer>();
		List<CompanyToBuilding> building = new ArrayList<CompanyToBuilding>();
		List<CompanyToSchoolUser> ids = new ArrayList<CompanyToSchoolUser>();
		//是校区
		if (2 == communityReal.getCommunityType()) {
			ids = this.dao().query(CompanyToSchoolUser.class, Cnd.where(Cnd.exps("companyId", "=", company.getId())),
					null);
			communityIds.add(communityReal.getId());
		} else {
			building = companyService.getCompanyToCommunity(company.getId());
			for (CompanyToBuilding buildCompany : building) {
				CommunityBuilding build = this.dao().fetch(CommunityBuilding.class, buildCompany.getBuildingId());
				communityIds.add(build.getCommunityId());
			}
		}
		List<SupplierToCommunity> supplierCompanyList = this.dao().query(SupplierToCommunity.class,
				Cnd.where("communityId", "in", communityIds));
		List<Integer> supplierIds = new ArrayList<Integer>();
		for (SupplierToCommunity stc : supplierCompanyList)
			supplierIds.add(stc.getSupplierId());
		List<Supplier> supplierList = this.dao().query(Supplier.class,
				Cnd.where("id", "in", supplierIds).and("offlineFlag", "=", Constants.ON_LINE));

		request.setAttribute("supplierList", supplierList);
		// 回传表单输入
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("orderCode", orderCode);
		itemMap.put("supName", supName);
		itemMap.put("startTime", startTime);
		itemMap.put("endTime", endTime);
		itemMap.put("status", status);
		itemMap.put("address", address);
		request.setAttribute("formdata", itemMap);

		// 订单列表
		return companyService.getOrderList(currentPage, orderCode, status, supName, building, startTime, endTime, ids,
				address);
	}

	/**
	 * 以往订单列表.
	 * 
	 * @param currentPage
	 * @param orderCode
	 * @param startTime
	 * @param endTime
	 * @param status
	 * @param request
	 * @return
	 */
	@At("/listOrderOld")
	@Ok("jsp:/product/oldCompanyOrder")
	public QueryResult listOrderOld(@Param("p") int currentPage, @Param("orderCode") String orderCode,
			@Param("address") String address, @Param("supName") String supName, @Param("status") String status,
			@Param("startTime") String startTime, @Param("endTime") String endTime, HttpServletRequest request,
			HttpSession session) {
		CompanyUser loginUser = (CompanyUser) session.getAttribute("companyUser");
		Company company = companyService.getCompany(loginUser.getCompanyId());
		Community communityReal = this.dao().fetch(Community.class, company.getCommunityId());
		List<Integer> communityIds = new ArrayList<Integer>();
		List<CompanyToBuilding> building = new ArrayList<CompanyToBuilding>();
		List<CompanyToSchoolUser> ids = new ArrayList<CompanyToSchoolUser>();
		//是校区
		if (2 == communityReal.getCommunityType()) {
			ids = this.dao().query(CompanyToSchoolUser.class, Cnd.where(Cnd.exps("companyId", "=", company.getId())),
					null);
			communityIds.add(communityReal.getId());
		} else {
			building = companyService.getCompanyToCommunity(company.getId());
			for (CompanyToBuilding buildCompany : building) {
				CommunityBuilding build = this.dao().fetch(CommunityBuilding.class, buildCompany.getBuildingId());
				communityIds.add(build.getCommunityId());
			}
		}
		List<SupplierToCommunity> supplierCompanyList = this.dao().query(SupplierToCommunity.class,
				Cnd.where("communityId", "in", communityIds));
		List<Integer> supplierIds = new ArrayList<Integer>();
		for (SupplierToCommunity stc : supplierCompanyList)
			supplierIds.add(stc.getSupplierId());
		List<Supplier> supplierList = this.dao().query(Supplier.class,
				Cnd.where("id", "in", supplierIds).and("offlineFlag", "=", Constants.ON_LINE));

		request.setAttribute("supplierList", supplierList);
		// 回传表单输入
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("orderCode", orderCode);
		itemMap.put("supName", supName);
		itemMap.put("startTime", startTime);
		itemMap.put("endTime", endTime);
		itemMap.put("status", status);
		itemMap.put("address", address);
		request.setAttribute("formdata", itemMap);

		// 订单列表
		return companyService.getOldOrderList(currentPage, orderCode, status, supName, building, startTime, endTime,
				ids, address);
	}

	/**
	 * 以往订单列表.
	 * 
	 * @param currentPage
	 * @param orderCode
	 * @param startTime
	 * @param endTime
	 * @param status
	 * @param request
	 * @return
	 */
	@At("/listOrderServer")
	@Ok("jsp:/product/serverCompanyOrder")
	public QueryResult listOrderServer(@Param("p") int currentPage, @Param("orderCode") String orderCode,
			@Param("supName") String supName, @Param("status") String status, @Param("startTime") String startTime,
			@Param("endTime") String endTime, HttpServletRequest request, HttpSession session) {
		CompanyUser loginUser = (CompanyUser) session.getAttribute("companyUser");
		Company company = companyService.getCompany(loginUser.getCompanyId());
		Community communityReal = this.dao().fetch(Community.class, company.getCommunityId());
		List<Integer> communityIds = new ArrayList<Integer>();
		List<CompanyToBuilding> building = new ArrayList<CompanyToBuilding>();
		List<CompanyToSchoolUser> ids = new ArrayList<CompanyToSchoolUser>();
		//是校区
		if (2 == communityReal.getCommunityType()) {
			ids = this.dao().query(CompanyToSchoolUser.class, Cnd.where(Cnd.exps("companyId", "=", company.getId())),
					null);
			communityIds.add(communityReal.getId());
		} else {
			building = companyService.getCompanyToCommunity(company.getId());
			for (CompanyToBuilding buildCompany : building) {
				CommunityBuilding build = this.dao().fetch(CommunityBuilding.class, buildCompany.getBuildingId());
				communityIds.add(build.getCommunityId());
			}
		}
		// 回传表单输入
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("orderCode", orderCode);
		itemMap.put("startTime", startTime);
		itemMap.put("endTime", endTime);
		itemMap.put("status", status);
		request.setAttribute("formdata", itemMap);

		// 订单列表
		return companyService.getServerOrderList(currentPage, orderCode, status, loginUser.getCompanyId(), building,
				startTime, endTime, ids);
	}

	/**
	 * 批量订单收货
	 */
	@At("/getOrder")
	@Ok("json")
	public String sendOrder(@Param("idStr") String idStr) {
		String[] idArray = idStr.split(",");
		for (String id : idArray) {
			supplierService.getOrder(Integer.valueOf(id));
		}
		return "{id:0}";
	}

	/**
	 * 服务站订单收货
	 */
	@At("/turnOne")
	@Ok("json")
	public String turnOne(@Param("id") int id) {
		supplierService.turnOrder(id);
		return "{id:0}";
	}

	/**
	 * 批量服务站订单收货
	 */
	@At("/turnOrder")
	@Ok("json")
	public String turnOrder(@Param("idStr") String idStr) {
		String[] idArray = idStr.split(",");
		for (String id : idArray) {
			supplierService.turnOrder(Integer.valueOf(id));
		}
		return "{id:0}";
	}

	/**
	 * 订单收货
	 */
	@At("/getOne")
	@Ok("json")
	public String getOne(@Param("id") int id) {
		supplierService.getOrder(id);
		return "{id:0}";
	}

	/**
	 * 提供服务
	 */
	@At("/serverOne/?")
	@Ok("json")
	public String serverOne(int id) {
		supplierService.serverOrder(id);
		return "{id:0}";
	}

	/**
	 * 批量提供服务
	 */
	@At("/turnServer")
	@Ok("json")
	public String turnServer(@Param("idStr") String idStr) {
		String[] idArray = idStr.split(",");
		for (String id : idArray) {
			supplierService.serverOrder(Integer.valueOf(id));
		}
		return "{id:0}";
	}

	@At("/buyOrderDetail")
	@Ok("jsp:/product/orderDetail")
	public QueryResult buyOrderDetail(@Param("orderCode") String orderCode, HttpServletRequest request) {
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("orderCode", orderCode);
		request.setAttribute("formdata", itemMap);
		ProductOrder goodsOrder = supplierService.getGoodsOrder(Integer.valueOf(orderCode));
		request.setAttribute("total", goodsOrder.getProductPrice());

		return supplierService.getOrderDetail(orderCode);
	}

	/**
	 * 代下订单密码验证（预处理）
	 */
	@At("/preAgentPasswordCheck/*")
	@Ok("jsp:/product/agentPasswordCheck")
	public void preAgentPasswordCheck(Integer community, Integer buildNo, String unitNo, Integer roomNo,
			String realName, HttpServletRequest request) {
		request.setAttribute("community", community);
		request.setAttribute("buildNo", buildNo);
		request.setAttribute("unitNo", unitNo);
		request.setAttribute("roomNo", roomNo);
		request.setAttribute("realName", realName);
		/*String username = supplierService.getAgentUserName(community, buildNo, unitNo, roomNo, realName);
		request.setAttribute("username", username);*/
	}

	/**
	 * 代下订单密码验证
	 */
	@At("/agentPasswordCheck/*")
	public String agentPasswordCheck(Integer community, Integer buildNo, String unitNo, Integer roomNo,
			String realName, String password, HttpServletRequest request) {
		String pwIsRight = supplierService.getAgentUserName(community, buildNo, unitNo, roomNo, realName, password);
		return pwIsRight;
	}

	//服务备注添加预处理
	@At("/preServiceRemark/?")
	@Ok("jsp:/communityServiceMange/serviceRemarkAdd")
	public void preServiceRemark(String id, HttpServletRequest request) {
		request.setAttribute("id", id);
	}

	//服务备注
	@At("/serviceRemarkSave")
	@Ok("jsp:/communityServiceMange/serviceRemarkAdd")
	public void serviceRemarkSave(@Param("id") int id, @Param("serviceRemark") String serviceRemark,
			HttpServletRequest request) {
		supplierService.serverOrderRemarkSave(id, serviceRemark);
		request.setAttribute("message", "操作成功");
	}

	@At("/viewOrder/?")
	@Ok("jsp:/product/viewOrder")
	public void viewOrder(@Param("id") int id, HttpServletRequest request) {

		// 订单
		ProductOrder order = supplierService.getGoodsOrder(id);
		request.setAttribute("order", order);

		// 订单商品列表
		QueryResult result = supplierService.getOrderProductList(id);
		request.setAttribute("productList", result.getList());

		//订单评价
		ProductComment orderComment = supplierService.getOrderComment(id);
		request.setAttribute("comment", orderComment);
	}

	/**
	 * 填写服务订单说明
	 * 
	 * @param currentPage
	 * @param orderCode
	 * @param startTime
	 * @param endTime
	 * @param status
	 * @param request
	 * @return
	 */
	@At("/listServiceRemark")
	@Ok("jsp:/product/listServiceRemark")
	public QueryResult listServiceRemark(@Param("p") int currentPage, @Param("orderCode") String orderCode,
			@Param("supName") String supName, @Param("status") String status, @Param("startTime") String startTime,
			@Param("endTime") String endTime, HttpServletRequest request, HttpSession session) {
		CompanyUser loginUser = (CompanyUser) session.getAttribute("companyUser");
		Company company = companyService.getCompany(loginUser.getCompanyId());
		Community communityReal = this.dao().fetch(Community.class, company.getCommunityId());
		List<Integer> communityIds = new ArrayList<Integer>();
		List<CompanyToBuilding> building = new ArrayList<CompanyToBuilding>();
		List<CompanyToSchoolUser> ids = new ArrayList<CompanyToSchoolUser>();
		//是校区
		if (2 == communityReal.getCommunityType()) {
			ids = this.dao().query(CompanyToSchoolUser.class, Cnd.where(Cnd.exps("companyId", "=", company.getId())),
					null);
			communityIds.add(communityReal.getId());
		} else {
			building = companyService.getCompanyToCommunity(company.getId());
			for (CompanyToBuilding buildCompany : building) {
				CommunityBuilding build = this.dao().fetch(CommunityBuilding.class, buildCompany.getBuildingId());
				communityIds.add(build.getCommunityId());
			}
		}
		// 回传表单输入
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("orderCode", orderCode);
		itemMap.put("startTime", startTime);
		itemMap.put("endTime", endTime);
		itemMap.put("status", status);
		request.setAttribute("formdata", itemMap);

		// 订单列表
		return companyService.getServerOrderListService(currentPage, orderCode, status, loginUser.getCompanyId(),
				building, startTime, endTime, ids);
	}

	/**
	 * 配货详情
	 * @param currentPage
	 * @param orderCode
	 * @param keyword
	 * @param nodeId
	 * @param status
	 * @param startTime
	 * @param community
	 * @param endTime
	 * @param productId
	 * @param request
	 * @param session
	 * @return
	 */
	@At("/receiveOrderDetail")
	@Ok("jsp:/product/receiveOrder")
	public void buyOrderDetail(@Param("startTime") String startTime, @Param("supplier") String supplier,
			HttpServletRequest request, HttpSession session) {
		CompanyUser loginUser = (CompanyUser) session.getAttribute("companyUser");
		Map<String, String> itemMap = new HashMap<String, String>();
		if (StringUtils.isBlank(startTime))
			startTime = sfd.format(new Date());
		itemMap.put("startTime", startTime);
		request.setAttribute("formdata", itemMap);
		// 配货列表
		List<ReadyProductVO> receiveOrderList = companyService.getReceiveOrderList(loginUser.getCompanyId(), startTime
				+ " 00:00:00", startTime + " 23:59:59", Constants.ORDER_STATUS_SHIPPED, supplier);
		request.setAttribute("receiveOrderList", receiveOrderList);

	}

	/**
	 * 订单打印用.
	 * 
	 * @param currentPage
	 * @param orderCode
	 * @param startTime
	 * @param endTime
	 * @param status
	 * @param request
	 * @return
	 */
	@At("/printSmallBillList")
	@Ok("jsp:/printInfo/printSmallBillPageListNew")
	public QueryResult printSmallBillList(@Param("p") int currentPage, @Param("orderCode") String orderCode,
			@Param("supName") String supName, @Param("status") String status, @Param("startTime") String startTime,
			@Param("endTime") String endTime, HttpServletRequest request, HttpSession session) {
		CompanyUser loginUser = (CompanyUser) session.getAttribute("companyUser");
		Company company = companyService.getCompany(loginUser.getCompanyId());
		Community communityReal = this.dao().fetch(Community.class, company.getCommunityId());
		List<Integer> communityIds = new ArrayList<Integer>();
		List<CompanyToBuilding> building = new ArrayList<CompanyToBuilding>();
		List<CompanyToSchoolUser> ids = new ArrayList<CompanyToSchoolUser>();
		//是校区
		if (2 == communityReal.getCommunityType()) {
			ids = this.dao().query(CompanyToSchoolUser.class, Cnd.where(Cnd.exps("companyId", "=", company.getId())),
					null);
			communityIds.add(communityReal.getId());
		} else {
			building = companyService.getCompanyToCommunity(company.getId());
			for (CompanyToBuilding buildCompany : building) {
				CommunityBuilding build = this.dao().fetch(CommunityBuilding.class, buildCompany.getBuildingId());
				communityIds.add(build.getCommunityId());
			}
		}
		List<SupplierToCommunity> supplierCompanyList = this.dao().query(SupplierToCommunity.class,
				Cnd.where("communityId", "in", communityIds));
		List<Integer> supplierIds = new ArrayList<Integer>();
		for (SupplierToCommunity stc : supplierCompanyList)
			supplierIds.add(stc.getSupplierId());
		List<Supplier> supplierList = this.dao().query(Supplier.class,
				Cnd.where("id", "in", supplierIds).and("offlineFlag", "=", Constants.ON_LINE));

		request.setAttribute("supplierList", supplierList);
		// 回传表单输入
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("orderCode", orderCode);
		itemMap.put("supName", supName);
		itemMap.put("startTime", startTime);
		itemMap.put("endTime", endTime);
		itemMap.put("status", status);
		request.setAttribute("formdata", itemMap);

		// 订单列表
		return companyService.getOldOrderList(currentPage, orderCode, status, supName, building, startTime, endTime,
				ids, "");
	}

	/**
	 * 测试快递通知.
	 */
	@At("/testPushMsgToOne")
	@Ok("jsp:/systemUser/testPushMsgToOne")
	public void testPushMsgToOne(HttpServletRequest req) {

	}

	@At("/sendMSG")
	public void sendMSG(HttpServletRequest req, @Param("mobile") String mobile, @Param("msg") String msg,
			HttpSession session) {
		CompanyUser loginUser = (CompanyUser) session.getAttribute("companyUser");
		ShopUser user = companyService.getUser(mobile);
		if (user != null) {
			ForumTopic ft = new ForumTopic();
			ft.setToId(user.getId());
			ft.setTopicTitle("快递通知");
			ft.setTopicContent(msg);
			forumC2UService.addTopic(ft, loginUser.getCompanyId());
		}
	}
}
